package com.pn.service.impl;

import com.pn.entity.OutStore;
import com.pn.entity.Result;
import com.pn.mapper.ProductMapper;
import com.pn.page.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.pn.mapper.OutStoreMapper;
import com.pn.service.OutStoreService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OutStoreServiceImpl implements OutStoreService {

    @Resource
    private OutStoreMapper outStoreMapper;
    @Resource
    private ProductMapper productMapper;

    @Override
    public Result saveOutStore(OutStore outStore) {
        int result = outStoreMapper.insertOutStore(outStore);
        if (result > 0) {
            return Result.ok("出库单添加成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "出库单添加失败！");
    }

    @Override
    public Page queryOutStorePage(Page page, OutStore outStore) {

        // 查询出库单
        List<OutStore> outStoreRows = outStoreMapper.selectOutStorePage(page, outStore);

        // 统计出库单总行数
        int count = outStoreMapper.countOutStore(outStore);

        page.setResultList(outStoreRows);
        page.setTotalNum(count);

        return page;
    }

    @Transactional
    @Override
    public Result confirmOutStore(OutStore outStore) {

        // 先去查询商品库存
        Integer invent = productMapper.findInventById(outStore.getProductId());
        if (invent < outStore.getOutNum()) {
            return Result.err(Result.CODE_ERR_BUSINESS, "商品库存不足!");
        }

        // 修改出库单状态 为1已出库
        int i = outStoreMapper.updateOutStoreIsOutById(outStore.getOutsId());

        if (i > 0) {
            // 修改商品库存
            Integer outNum = outStore.getOutNum();
            outNum = -outNum;
            int j = productMapper.updateInventById(outStore.getProductId(), outNum);
            if (j > 0) {
                return Result.ok("出库成功！");
            }
            return Result.err(Result.CODE_ERR_BUSINESS, "出库失败！");
        }

        return Result.err(Result.CODE_ERR_BUSINESS, "出库失败！");
    }
}
